using System;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MsgBackend.Api.Models;
using MsgBackend.Api.ParamModel;
using MsgBackend.Api.Repository;
using MsgBackend.Api.Utils;

namespace MsgBackend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ArticleController : ControllerBase
    {
        private IRepository<Articles> _ArticlesRepository;

        private IRepository<Admins> _AdminsRepository;

        private IRepository<ArticlesPicture> _ArticlesPicture;

        private IRepository<ArticleType> _ArticleType;

        private readonly IConfiguration _configuration;

        private readonly IWebHostEnvironment _hostingEnvironment;

        public ArticleController(
            IConfiguration configuration,
            IRepository<Articles> articlesrepository,
            IRepository<Admins> AdminsRepository,
            IRepository<ArticlesPicture> ArticlesPicture,
            IWebHostEnvironment hostingEnvironment,
            IRepository<ArticleType> ArticleType
        )
        {
            _ArticlesRepository = articlesrepository;
            _configuration = configuration;
            _AdminsRepository = AdminsRepository;
            _ArticlesPicture = ArticlesPicture;
            _ArticleType = ArticleType;
            _hostingEnvironment = hostingEnvironment;
        }

        //获取所有书籍
        [HttpGet, Route("Articles")]
        public ActionResult GetArticles()
        {
            var article = _ArticlesRepository.Table;
            return Ok(new { Code = 1000, Data = article, Msg = "获得成功" });
        }

        //根据文章id获取
        [HttpGet("GetOne/{id}")]
        public ActionResult GetOne(int id)
        {
            var article = _ArticlesRepository.GetById(id);
            return Ok(new { Code = 1000, Data = article, Msg = "获取成功" });
        }

        //根据类别id获取
        [HttpGet("GetTypeOne/{id}")]
        public ActionResult GetTypeOne(int id)
        {
            var articles = _ArticlesRepository.Table;
            var article = articles.Where(x => x.ArticleTypeId == id);
            return Ok(new { Code = 1000, Data = article, Msg = "获取成功" });
        }

        //添加新的文章
        [HttpPost, Route("AddArticle")]
        public ActionResult AddArticle(ParamArticle model)
        {
            var article =
                new Articles {
                    //文章是否发布
                    IsActived = model.isActived,
                    ArticleName = model.ArticleName,
                    ArticleTitle = model.ArticleTitle,
                    ArticleAbstract = model.ArticleAbstract,
                    ArticleContent = model.ArticleContent,
                    //管理员id
                    Admins =
                        _AdminsRepository
                            .Table
                            .Single(r => r.Id == model.AdminId),
                    //图片id
                    ArticlesPicture =
                        _ArticlesPicture
                            .Table
                            .Single(r => r.Id == model.ArticlesPictureId),
                    //文章类型Id
                    ArticleType =
                        _ArticleType
                            .Table
                            .Single(r => r.Id == model.ArticleTypeId)

                    // ArticleTypeId=model.ArticleTypeId,
                    // AdminsId=model.AdminsId,
                    // ArticlesPictureId=model.ArticlesPictureId,
                    // ArticleStatusId=model.ArticleStatusId
                };

            _ArticlesRepository.Insert (article);
            return Ok(new {
                Code = 1000,
                Data =
                    new ReturnArticles {
                        ArticleName = model.ArticleName,
                        ArticleTitle = model.ArticleTitle,
                        ArticleAbstract = model.ArticleAbstract,
                        ArticleContent = model.ArticleContent,
                        ArticleTypeId = model.ArticleTypeId
                    },
                Msg = "添加成功"
            });
        }

        //根据文章名查询
        [HttpGet("ArticleName")]
        public ActionResult ArticleName([FromQuery] SelectMsg data)
        {
            var msg = data.msg;

            //获取当前页
            var currentPage = data.currentPage;

            //获取页面数据行数
            var pageSize = data.pageSize;
            var articles = _ArticlesRepository.Table;

            var article =
                articles
                    .Where(x => x.ArticleName.Contains(msg))
                    .Where(x => x.IsDeleted == false)
                    .Take(pageSize)
                    .ToList();

            if (article == null)
            {
                return Ok(new { Code = 1002, Data = " ", Msg = "未查询到" });
            }
            else
            {
                return Ok(new {
                    Code = 1000,
                    Data = article,
                    Count =
                        articles
                            .Where(x => x.ArticleName.Contains(msg))
                            .Where(x => x.IsDeleted == false)
                            .Count(),
                    Msg = "获得成功"
                });
            }
        }

        //删除文章
        [HttpDelete("{id}")]
        public ActionResult DeleteArticle(int id)
        {
            var article = _ArticlesRepository.GetById(id);
            if (article != null)
            {
                article.IsActived = false;
                article.IsDeleted = true;
                article.UpdatedTime = DateTime.Now;
                _ArticlesRepository.Delete (article);
                return Ok(new {
                    Code = 1000,
                    Data = article,
                    Msg = "删除成功"
                });
            }
            else
            {
                return Ok(new { Code = 1001, Data = " ", Msg = "删除失败" });
            }
        }

        //修改文章内容
        [HttpPut("{id}")]
        public ActionResult UpdateArticle(ParamArticle model, int id)
        {
            var articles = _ArticlesRepository.GetById(id);
            if (articles != null)
            {
                articles.ArticleName = model.ArticleName;
                articles.ArticleTitle = model.ArticleTitle;
                articles.ArticleAbstract = model.ArticleAbstract;
                articles.ArticleContent = model.ArticleContent;

                _ArticlesRepository.Update (articles);
                return Ok(new {
                    Code = 1000,
                    Data = articles,
                    Msg = "修改成功"
                });
            }
            return Ok(new { Code = 1002, Data = "", Msg = "修改失败" });
        }

        //根据类型id获得对应文章
        [HttpGet("ArticletypeId/{id}")]
        public ActionResult ArticleType(int id)
        {
            var Articles = _ArticlesRepository.Table;
            var ArtyclesType = Articles.Where(x => x.ArticleTypeId == id);
            return Ok(new {
                Code = 1000,
                Data = ArtyclesType,
                Msg = "获得成功"
            });
        }

        //后台获取所有书籍
        [HttpGet, Route("Articlesbacken")]
        public ActionResult GetArticlesBacken([FromQuery] Pager pager)
        {
            Console.WriteLine(pager.currentPage);

            //获取当前页
            var currentPage = pager.currentPage;

            //获取页面数据行数
            var pageSize = pager.pageSize;
            var articles = _ArticlesRepository.Table;
            var article =
                articles
                    .Where(x => x.IsDeleted == false)
                    .Skip((currentPage - 1) * pageSize)
                    .Take(pageSize)
                    .ToList();
            return Ok(new {
                Code = 1000,
                Data = article,
                Count = articles.Where(x => x.IsDeleted == false).Count(),
                Msg = "获得成功"
            });
        }

        //修改文章状态
        [HttpPut, Route("statu")]
        public ActionResult PutStatu(Status model)
        {
            Console.WriteLine(model.id);
            Console.WriteLine(model.isActived);
            var article = _ArticlesRepository.GetById(model.id);
            if (article != null)
            {
                if (model.isActived == false)
                {
                    article.IsActived = false;
                    _ArticlesRepository.Update (article);
                    return Ok(new {
                        Code = 1000,
                        Data = article,
                        Msg = "修改成功"
                    });
                }
                else
                {
                    article.IsActived = true;
                    _ArticlesRepository.Update (article);
                    return Ok(new {
                        Code = 1000,
                        Data = article,
                        Msg = "修改成功"
                    });
                }
            }
            return Ok(new {
                Code = 1002,
                Data = "",
                Msg = "获取失败，请检查id是否正确"
            });
        }

        // 添加图片
        //Post /article/addpic
        [HttpPost, Route("addpic")]
        public dynamic AddPicture()
        {
            var files = HttpContext.Request.Form.Files;

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot
            var showfilePath =
                PicHelper.getFilePath(files, "upload", webRootPath);

            Console.WriteLine (showfilePath);

            return Ok(new {
                Code = 1000,
                Data = showfilePath,
                Msg = "添加图片成功"
            });
        }

        // 编辑图片
        [HttpPut, Route("addpic")]
        public dynamic EditPicture()
        {
            var files = HttpContext.Request.Form.Files;

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot
            var showfilePath =
                PicHelper.getFilePath(files, "upload", webRootPath);

            Console.WriteLine (showfilePath);

            return Ok(new {
                Code = 1000,
                Data = showfilePath,
                Msg = "编辑图片成功"
            });
        }

        //删除文章图片
        //Post /article/deletepic
        [HttpPut, Route("deletepic")]
        public dynamic Put(ParamArticle model)
        {
            var str = model.PicPath;

            string webRootPath = _hostingEnvironment.WebRootPath; // ...Api/wwwroot

            var picpath = webRootPath + str;

            FileHelper.FileDel (picpath);

            return "Ok";
        }
    }
}
